package datapack

import (
	"broker/interface/imodel"
	"broker/struct/model"
	"encoding/binary"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/4/25 10:46 下午
 **/

type PublishDataPack struct {
	pubMsg *model.PublishMessage
}

func NewPublishDataPack(pubMsg *model.PublishMessage) *PublishDataPack {
	return &PublishDataPack{
		pubMsg: pubMsg,
	}
}

func (p PublishDataPack) Pack(message imodel.IMessage) ([]byte, error) {
	pubMsg := message.(*model.PublishMessage)

	///封包topic
	pdp := NewParamDataPack(nil)
	msgData := pdp.Pack(pubMsg.Topic)
	if pubMsg.Qos > 0 {
		//封包报文标识符
		packetIDList := make([]byte, 2)
		binary.BigEndian.PutUint16(packetIDList, pubMsg.PacketID)
		msgData = append(msgData, packetIDList...)
	}
	//封包数据
	msgData = append(msgData, pubMsg.Payload...)
	return msgData, nil
}

func (p PublishDataPack) UnPack(bytes []byte) (imodel.IMessage, error) {
	pdp := NewParamDataPack(bytes)
	//解包主题名
	topic, err := pdp.UnPack()
	if err != nil {
		return nil, err
	}
	p.pubMsg.Topic = topic.GetData()
	if p.pubMsg.Qos > 0 {
		//解包报文标识符
		packetID, err := pdp.UnPackByLen(2)
		if err != nil {
			return nil, err
		}
		err = binary.Read(packetID.GetDataBuffer(), binary.BigEndian, &p.pubMsg.PacketID)
		if err != nil {
			return nil, err
		}
	}
	//解包负载数据
	payload, err := pdp.UnPackAll()
	if err != nil {
		return nil, err
	}
	p.pubMsg.Payload = payload.GetData()
	return p.pubMsg, nil
}
